package com.smartkey.utils;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;

public class PackageUtils {

	private static final String TAG = "PackageUtils";
	public static final String META_DATA_KEY_CHANNEL = "MOBILE_CHANNEL";
	public static final String META_DATA_KEY_SOURCEID = "MOBILE_SOURCEID";

	private static PackageUtils instance;

	private PackageManager packageManager;
	private Context context;

	private PackageUtils(Context context) {
		this.context = context;
	}

	public static PackageUtils getInstance(Context context) {
		if (instance == null) {
			instance = new PackageUtils(context);
			instance.getPackageManager();
		}
		return instance;
	}

	/**
	 * 获取包管理器
	 * 
	 * @return
	 */
	public PackageManager getPackageManager() {
		if (packageManager == null) {
			packageManager = context.getPackageManager();
		}
		return packageManager;
	}

	/**
	 * 获取包信息
	 * 
	 * @return
	 */
	public PackageInfo getPackageInfo() {
		try {
			PackageInfo packInfo = packageManager.getPackageInfo(
					context.getPackageName(), 0);
			return packInfo;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取包名
	 * 
	 * @return
	 */
	public String getPackageName() {
		return getPackageInfo().packageName;
	}

	/**
	 * 获取版本号
	 * 
	 * @return
	 */
	public int getVersionCode() {
		return getPackageInfo().versionCode;
	}

	/**
	 * 获取版本名称
	 * 
	 * @return
	 */
	public String getVersionName() {
		return getPackageInfo().versionName;
	}

	/**
	 * 判断应用是否已安装
	 * 
	 * @param packageInfo
	 * @return
	 */
	public boolean isInstalled(String packageName) {
		PackageInfo packageInfo = null;
		boolean result = false;
		try {
			packageInfo = this.getPackageManager().getPackageInfo(packageName,
					0);
			result = packageInfo != null;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		} finally {
			packageInfo = null;
		}
		return result;
	}

	public PackageInfo getPackageInfo(String packageName) {
		PackageInfo packageInfo = null;
		try {
			packageInfo = this.getPackageManager().getPackageInfo(packageName,
					0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return packageInfo;
	}

	public String getInstallPackageNames() {
		List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
		for (PackageInfo packageInfo : packageInfos) {
			if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
				// 非系统应用
				// Log.d(TAG, "非系统应用");
			} else {
				// 系统应用　　
				// LogUtils.d(TAG, "packageName:" + packageInfo.packageName);
				LogUtils.d(TAG, "系统应用");
			}
		}
		return "";

	}

	/**
	 * 获取正在运行桌面包名（注：存在多个桌面时且未指定默认桌面时，该方法返回Null,使用时需处理这个情况）
	 * 注：存在多个桌面时且未指定默认桌面时，该方法返回Null,使用时需处理这个情况；
	 */
	public String getLauncherPackageName() {
		final Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		final ResolveInfo res = packageManager.resolveActivity(intent, 0);
		if (res.activityInfo == null) {
			// should not happen. A home is always installed, isn't it?
			return null;
		}
		if (res.activityInfo.packageName.equals("android")) {
			// 有多个桌面程序存在，且未指定默认项时；
			return null;
		} else {
			return res.activityInfo.packageName;
		}
	}

	public String getLauncherDBAuthority() {
		String packageName = getLauncherPackageName();
		if (packageName == null) {
			return null;
		}
		ApplicationInfo applicationInfo;
		try {
			applicationInfo = packageManager.getApplicationInfo(packageName, 0);
			if (applicationInfo != null) {
				List<ProviderInfo> providers = packageManager
						.queryContentProviders(applicationInfo.processName,
								applicationInfo.uid, 0);
				if (providers != null) {
					for (ProviderInfo providerInfo : providers) {
						LogUtils.d(TAG, providerInfo.authority);
						return providerInfo.authority;
					}
				}
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取应用渠道号
	 * 
	 * @param context
	 * @return
	 */
	public final String getMetaData(String meta_data_key) {
		try {
			PackageManager packageManager = getPackageManager();
			ApplicationInfo applicationInfo = packageManager
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);
			if (applicationInfo != null && applicationInfo.metaData != null) {
				return String.valueOf(applicationInfo.metaData
						.get(meta_data_key));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 获取平台来源
	 * 
	 * @return
	 */
	public final String getSourceId() {
		return getMetaData(META_DATA_KEY_SOURCEID);
	}

	/**
	 * 获取渠道ID
	 * 
	 * @return
	 */
	public final String getChannel() {
		return getMetaData(META_DATA_KEY_CHANNEL);
	}

}
